<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Models\Common;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $guarded = [];

    /**
     * 自己与自己关联
     * 一级分类下得二级分类
     * 一对一关联
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id', 'id');
    }

    static function CreateModel( $data )
    {
        return self::create($data);
    }

    static function GetModel( $where = [], $with = [], $select = [ '*' ] )
    {
        return self::with($with)->where($where)->select($select)->orderBy('sort_order')->orderBy('created_at', 'desc')->get();//一级分类
    }

    static function CheckChildren( $id )
    {
        $category = self::with([
            'children' => function ( $query ) {
                $query->select('id');
            },
        ])->select([
            'id', 'parent_id',
        ])->find($id);
        if ( $category->children->isEmpty() ) return TRUE;
        return FALSE;
    }

    static function UpdateModel( $where = [], $data = [] )
    {
        return self::where($where)->update($data);
    }

    static function DestroyModel( $id )
    {
        return self::destroy($id);
    }

    static function FindModel( $id, $with = [], $select = [ '*' ] )
    {
        return self::with($with)->select($select)->find($id);
    }
}
